﻿using hCommand;
using System;
using System.Security.Cryptography;

namespace Persistence {
    public class CsdSaveEngine : GkTransaction {
        public CoreStockDet csd;
        //status count  doiType  itemId
        protected override TransRes Execute() {
            WhDoiDet doiDet = getById<WhDoiDet>(csd.doiDetId);
            if (doiDet != null && doiDet.planCount < doiDet.activeCount+ csd.countDb) {
                return new TransRes("实际大于计划数量");
            }
            doiInfo(csd);
            csInfo(csd);
            csd.changeTime = DateTime.Now;

            CoreItem item = getById<CoreItem>(csd.itemId);
            if (csd.id == 0) { 
                if (item.fenlei == 1) {
                    double count = csd.countDb;
                    csd.countDb = 1;
                    BParam p = getById<BParam>(12);
                    long begin = p.v;
                    for (int i = 0; i < count; i++) {
                        CoreStockDet det = (CoreStockDet)csd.Clone();
                        det.barCode = "" + begin++;
                        insert(det);
                    }
                    p.v = begin;
                    update(p);
                } else {
                    insert(csd);
                }
            } else {
                update(csd);
            }
            doiActive( csd.doiDetId); 
            return new TransRes();
        }
         public void doiActive( long id) {
            if (id == 0) {
                return;
            }
            string sql1 = $@"update Wh_Doi_det set active_Count=(select IFNULL( sum(Count_Db),0) from core_stock_det  where doi_det_Id=@id and status<{(int)StockStatus.上限}) where id=@id ";
            exec(sql1, new { id });

            String sql = "update wh_doi set status=2 where id= (SELECT pid FROM wh_doi_det  where id=@id and   active_Count>0)";
            exec(sql, new { id });

        }

        void doiInfo(CoreStockDet csd) {
            WhDoiDet det = getById<WhDoiDet>(csd.doiDetId);
            if (det != null) {
                WhDoi doi = getById<WhDoi>(det.pid);
                csd.batchNo = doi.batchNo;
                csd.doiType = DetConst.DoiTypeDj;
                csd.unit = det.unit;
                csd.itemId = det.itemId;
            }
        }
        void csInfo(CoreStockDet csd) {
            if (csd.pid > 0) {
                CoreStock cs = getById<CoreStock>(csd.pid);
                csd.pCode = cs.boxCode;
            }

        }

       
    }
}
